package com.atguigu.eduorder.controller;

import com.atguigu.commonutils.JwtUtils;
import com.atguigu.eduorder.entity.Order;
import com.atguigu.eduorder.service.OrderService;
import com.atguigu.commonutils.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @descriptions: 订单 前端控制器
 * @author: pandengZhu
 * @date: 2024/5/10 21:51
 * @version: 1.0
 */

@Api(tags = "微信支付订单")
@RestController
@RequestMapping("/eduorder/order")
//@CrossOrigin
public class OrderController {

    @Resource
    private OrderService orderService;

    /**
     * 根据课程id和 用户id创建订单，返回订单id
     *
     * @param courseId 课程id
     * @param request  获取会员id
     * @return 订单号
     */
    @ApiOperation("创建微信订单")
    @PostMapping("/createOrder/{courseId}")
    public R createOrder(@ApiParam(value = "课程id", required = true)
                         @PathVariable String courseId, HttpServletRequest request) {

        //1.通过jwtutil工具类获取会员id
        //String memberId = JwtUtil.getUserId(request.getHeader("token"));
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        //2.创建订单，返回订单号
        String orderNo = orderService.createOrder(courseId, memberId);
        return R.ok().data("orderId", orderNo);
    }

    @ApiOperation("根据id获取订单信息接口")
    @GetMapping("/getOrderInfo/{orderId}")
    public R getOrderInfo(@ApiParam(value = "订单id", required = true)
                          @PathVariable String orderId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderId);
        Order order = orderService.getOne(queryWrapper);

        return R.ok().data("item", order);
    }

    @ApiOperation("根据课程id和会员id查询订单表中订单状态")
    @GetMapping("/isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@ApiParam(value = "课程id", required = true)
                         @PathVariable String courseId,
                         @ApiParam(value = "会员id", required = true)
                         @PathVariable String memberId) {

        //订单状态是1表示支付成功
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId).eq("member_id", memberId).eq("status", 1);
        int count = orderService.count(queryWrapper);
        if (count > 0) {
            return true;//已支付
        }else {
            return false;//未支付
        }
    }

}
